<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : '编辑'"
    :close-on-click-modal="false"
    append-to-body
    :visible.sync="visible"
    class="jsbos-dialog jsbos-dialog_center"
    lock-scroll
    width="600px"
  >
    <el-row :gutter="15" class="">
      <el-form
        ref="elForm"
        :model="dataForm"
        :rules="rules"
        size="small"
        label-width="100px"
        label-position="right"
      >
        <template v-if="!loading">
          <el-col :span="24">
            <el-form-item label="上级目录" prop="parentId">
              <tree-select
                ref="parentTreeSelectRef"
                v-model="dataForm.parentId"
                :options="treeData"
                :props="treeProps"
                placeholder="选择上级目录"
                @change="onChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目录编码" prop="enCode">
              <el-input
                v-model="dataForm.enCode"
                placeholder="请输入"
                :maxlength="50"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目录名称" prop="fullName">
              <el-input
                v-model="dataForm.fullName"
                placeholder="请输入"
                :maxlength="50"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效标志" prop="enabledMark">
              <el-switch
                v-model="dataForm.enabledMark"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="全局标识" prop="globalMark">
              <el-select
                v-model="dataForm.globalMark"
                placeholder="请选择"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in globalMarkOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dataForm.globalMark == '2'">
            <el-form-item label="所属组织" prop="organizeTdsTree">
              <com-select
                v-model="dataForm.organizeTdsTree"
                placeholder="请选择"
                clearable
                :multiple="true"
              >
              </com-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sortCode">
              <el-input-number
                v-model="dataForm.sortCode"
                placeholder="排序"
                :max="10000"
                :step="1"
                controls-position="right"
              >
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="dataForm.description"
                placeholder="请输入"
                :maxlength="500"
                :style="{ width: '100%' }"
                true
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" @click="visible = false">
        取 消</el-button
      >
      <el-button :loading="btnLoading" type="primary" @click="dataFormSubmit()">
        确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import {
  getInfo,
  Update,
  Create,
  getCategorySelector,
} from "@/views/exam/api/category";
export default {
  components: {},
  props: {
    folderType: {
      type: String,
      default: "paper",
    },
  },
  data() {
    return {
      isAdministrator: false,
      companyId: "",
      menuId: "",
      visible: false,
      loading: false,
      btnLoading: false,
      treeData: [],
      treeProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
      parentIds: [],
      treeNames: [],
      dataForm: {
        folderType: this.folderType,
        enCode: "",
        fullName: "",
        parentId: "",
        sortCode: 0,
        parentIds: "",
        treeNames: "",
        description: "",
        enabledMark: 1,
        globalMark: "1",
        organizeTdsTree: [],
        companyId: "",
        creatorUserId: "",
        creatorTime: "",
        lastModifyUserId: "",
        lastModifyTime: "",
        deleteUserId: "",
        deleteTime: "",
        deleteMark: 0,
      },
      rules: {
        enCode: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        fullName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        parentId: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        sortCode: [
          {
            required: true,
            message: "排序",
            trigger: ["blur", "change"],
          },
        ],
        enabledMark: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        globalMark: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        organizeTdsTree: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        companyId: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        deleteMark: [
          {
            required: true,
            message: "不能为空",
            trigger: "change",
          },
        ],
      },
      globalMarkOptions: [
        { fullName: "全局", id: "1" },
        { fullName: "组织", id: "2" },
      ],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.isAdministrator = this.$store.getters.userInfo.isAdministrator;
    this.companyId = this.$store.getters.userInfo.organizeId;
  },
  mounted() {},
  methods: {
    onChange(val) {
      console.log(val);
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id, menuId) {
      this.menuId = menuId || "";
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        // 获取上级
        getCategorySelector({
          folderType: this.folderType,
          parentId: "-1",
          menuId: this.menuId,
        }).then((res) => {
          let topItem = {
            fullName: "全部",
            hasChildren: true,
            id: "-1",
            children: res.data,
          };
          this.treeData = [topItem];
        });

        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.folderType = this.folderType;
          this.dataForm.enabledMark = 1;
          this.dataForm.globalMark = "1";
          this.dataForm.sortCode = 0;
          this.dataForm.deleteMark = 0;
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          var _data = this.dataList();
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    settingTreeNames(e) {
      console.log(e);
      var selectTree = this.$refs.parentTreeSelectRef.$refs.selectTree;
      // 选中节点的所有父级id和label信息
      this.parentIds = [];
      this.treeNames = [];
      this.getTreeNode(selectTree.getNode(e));
      console.log(selectTree.getNode(e));
      console.log("this.parentIds", this.parentIds);
      console.log("this.treeNames", this.treeNames);
    },
    getTreeNode(node) {
      console.log("node", node);
      if (node) {
        if (node.label !== undefined && node.data.id != "-1") {
          this.parentIds.unshift(node.data.id);
          this.treeNames.unshift(node.label);
          this.getTreeNode(node.parent);
        }
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.enabledMark = parseInt(_data.enabledMark);
      _data.deleteMark = parseInt(_data.deleteMark);
      if (_data.globalMark == "1") {
        _data.organizeTdsTree = "[]";
      } else {
        _data.organizeTdsTree = JSON.stringify(_data.organizeTdsTree);
      }
      this.settingTreeNames(_data.parentId);
      var _parentIds = JSON.parse(JSON.stringify(this.parentIds));
      var _treeNames = JSON.parse(JSON.stringify(this.treeNames));
      _parentIds.unshift("-1");
      _treeNames.push(_data.fullName);
      console.log("this.parentIds", _parentIds);
      console.log("this.treeNames", _treeNames);
      _data.parentIds = _parentIds.join(",");
      _data.treeNames = _treeNames.join("/");
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.enabledMark = parseInt(_dataAll.enabledMark);
      _dataAll.organizeTdsTree = JSON.parse(_dataAll.organizeTdsTree);
      _dataAll.deleteMark = parseInt(_dataAll.deleteMark);
      this.dataForm = _dataAll;
    },
  },
};
</script>
